const axios = require("axios");
const cheerio = require("cheerio");

// 定义一个异步函数 fetchVideoLinks，用于从指定 URL 抓取视频链接
async function fetchVideoLinks(url, type, res) {
  try {
    const response = await axios.get(url);
    const $ = cheerio.load(response.data);

    let filteredLinks = [];
    $(".module-poster-item").each((index, item) => {
      const title = $(item).attr("title");
      const img = $(item).find("img").attr("data-original");
      const href = $(item).attr("href");
      // 如果 type 为 "all" 或者标题包含指定的 type，则将该链接添加到 filteredLinks 数组中
      if (type === "all" || title.toLowerCase().includes(type.toLowerCase())) {
        filteredLinks.push({
          img,
          href,
          title,
        });
      }
    });

    // 将过滤后的链接数组发送给客户端
    res.send({ code: 200, module: filteredLinks });
  } catch (error) {
    console.error("Error fetching video links");
  }
}

module.exports = fetchVideoLinks;
